//配置axios 请求拦截和返回拦截
import axios from 'axios';

axios.defaults.timeout = 3*60*1000; //超时终止请求

if (process.env.NODE_ENV !== 'development') {
    axios.defaults.baseURL = 'http://127.0.0.1:8001';  //配置公共域名前缀 打包后
}else{
    axios.defaults.baseURL = "/api"; //开发环境
}

//自定义post方法
axios.my_post = function(url,data){  //（表单）
    var params = new URLSearchParams();
    for(let a in data) {
        params.append(a, data[a]);
    }
    return axios.post(url,params);
}
axios.post_file = function(url,data){  //文件
    var params = new FormData();
    let user_data = sessionStorage.getItem('user_data');
    if(user_data){
        user_data = JSON.parse(user_data);
    }
    params.append('userId',user_data.userId);
    for(let a in data) {
        params.append(a, data[a]);
    }
    return axios.post(url,params);
}
axios.json_post = function(url,data={}){  //JSON
    let user_data = sessionStorage.getItem('user_data');
    if(user_data){
        user_data = JSON.parse(user_data);
        data.userId = user_data.userId;
    }
    return axios.post(url,data);
}
//http request 拦截器
axios.interceptors.request.use(
    config => {
        config.data && config.data instanceof URLSearchParams ?
            config.headers = {
                'Content-Type':'application/x-www-form-urlencoded'
            } : config.data instanceof FormData ?
                config.headers = {
                    'Content-Type': 'multipart/form-data'
                } :
                config.headers = {
                    'Content-Type': 'application/json;charset=UTF-8'
                };
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);
//http response 拦截器
axios.interceptors.response.use(
    response => {
        let message = response.data.msg;
        let sate = response.data.sate;
        if (sate == 200 ){
            return Promise.resolve(response.data);
        }else if(sate==201){
            sessionStorage.removeItem('user_data');
            location.reload();
        }else{
            return Promise.reject(message);
        }
    },
    error => {
        return Promise.reject(error);
    }
)

export default axios;
